import { useState } from 'react';
import { MdEditor, ModalToolbar } from 'md-editor-rt';
import { useModel } from '@umijs/max';

interface ReadExtensionProp {
  mdText: string;
}

const ReadExtension = (props: ReadExtensionProp) => {
  const [state, setState] = useState({
    visible: false,
    modalFullscreen: false,
  });

  const mdHeadingId = (_: string, __: string | number, index: number) => `heading-${index}`;

  const { markDownStore } = useModel('markDown');

  return (
    <ModalToolbar
      visible={state.visible}
      isFullscreen={state.modalFullscreen}
      showAdjust
      title="弹窗预览"
      modalTitle="编辑预览"
      width="870px"
      height="600px"
      onClick={() => {
        setState({
          ...state,
          visible: true,
        });
      }}
      onClose={() => {
        setState({
          ...state,
          visible: false,
        });
      }}
      onAdjust={() => {
        setState({
          ...state,
          modalFullscreen: !state.modalFullscreen,
        });
      }}
      trigger={
        <svg className="md-editor-icon" aria-hidden="true">
          <use xlinkHref="#icon-read" />
        </svg>
      }
    >
      {state.visible ? (
        <>
          <div
            style={{
              height: '100%',
              padding: '20px',
              overflow: 'auto',
            }}
          >
            <MdEditor
              theme={markDownStore.theme}
              language={markDownStore.lang}
              previewTheme={markDownStore.previewTheme}
              codeTheme={markDownStore.codeTheme}
              editorId="md-editor-preview"
              mdHeadingId={mdHeadingId}
              modelValue={props.mdText}
            />
          </div>
        </>
      ) : (
        <></>
      )}
    </ModalToolbar>
  );
};

export default ReadExtension;
